package com.ruoyi.goods.controller;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import javax.servlet.http.HttpServletResponse;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.constant.GoodsConstants;
import com.ruoyi.common.enums.PriceMode;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.order.OrderUtils;
import com.ruoyi.enterwarehouse.domain.WEnterWarehouseInfo;
import com.ruoyi.enterwarehouse.service.IWEnterWarehouseInfoService;
import com.ruoyi.exitwarehouse.domain.WExitWarehouseInfo;
import com.ruoyi.exitwarehouse.service.IWExitWarehouseInfoService;
import com.ruoyi.goods.domain.TGoodsWeightSum;
import com.ruoyi.transfers.service.IWGoodsTransferInfoService;
import com.ruoyi.warehouse.service.IWWarehouseFeeAccountService;
import com.ruoyi.waybill.domain.TWayBillInfo;
import com.ruoyi.waybill.service.ITWayBillInfoService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.goods.domain.TGoodsInfo;
import com.ruoyi.goods.service.ITGoodsInfoService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 货物信息Controller
 * 
 * @author wzy
 * @date 2024-08-25 16:58:34
 */
@RestController
@RequestMapping("/goods/good")
public class TGoodsInfoController extends BaseController
{
    /** 状态码 */
    private static final Integer UPDATE_WAYBILL = 1;
    private static final Integer UPDATE_ENTERNUMBER = 2;
    private static final Integer UPDATE_ENTERCHECK = 3;
    private static final Integer UPDATE_EXITNUMBER = 4;
    private static final Integer UPDATE_EXITCHECK = 5;

    private static final Integer REMOVE_WAYBILL = 1;
    private static final Integer REMOVE_ENTERNUMBER = 2;
    private static final Integer REMOVE_EXITNUMBER = 4;

    @Autowired
    private ITGoodsInfoService tGoodsInfoService;

    @Autowired
    private ITWayBillInfoService tWayBillInfoService;

    @Autowired
    private IWEnterWarehouseInfoService wEnterWarehouseInfoService;

    @Autowired
    private IWExitWarehouseInfoService wExitWarehouseInfoService;

    @Autowired
    private IWWarehouseFeeAccountService wWarehouseFeeAccountService;

    @Autowired
    private IWGoodsTransferInfoService wGoodsTransferInfoService;

    private static Logger logger = LoggerFactory.getLogger(TGoodsInfoController.class);
    /**
     * 查询货物信息列表
     */
    @PreAuthorize("@ss.hasPermi('goods:good:list')")
    @GetMapping("/list")
    public TableDataInfo list(TGoodsInfo tGoodsInfo)
    {
        String bundleNumber = tGoodsInfo.getBundleNumber();
        if(StringUtils.isNotEmpty(bundleNumber)) {
            tGoodsInfo.setBundleNumber(bundleNumber.replace(",", "|"));
        }
        startPage();
        List<TGoodsInfo> list = tGoodsInfoService.selectTGoodsInfoList(tGoodsInfo);
        return getDataTable(list);
    }

    /**
     * 导出货物信息列表
     */
    @PreAuthorize("@ss.hasPermi('goods:good:export')")
    @Log(title = "货物信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, TGoodsInfo tGoodsInfo)
    {
        String bundleNumber = tGoodsInfo.getBundleNumber();
        if(StringUtils.isNotEmpty(bundleNumber)) {
            tGoodsInfo.setBundleNumber(bundleNumber.replace(",", "|"));
        }
        List<TGoodsInfo> list = tGoodsInfoService.selectTGoodsInfoList(tGoodsInfo);
        ExcelUtil<TGoodsInfo> util = new ExcelUtil<TGoodsInfo>(TGoodsInfo.class);
        util.exportExcel(response, list, "货物信息数据");
    }

    /**
     * 获取货物信息详细信息
     */
    @PreAuthorize("@ss.hasPermi('goods:good:query')")
    @GetMapping(value = "/{goodsId}")
    public AjaxResult getInfo(@PathVariable("goodsId") Long goodsId)
    {
        return success(tGoodsInfoService.selectTGoodsInfoByGoodsId(goodsId));
    }

    /**
     * 新增货物信息
     */
    /*解决入库，货物增删改问题，暂时屏蔽后端权限校验；需增加入库，货物增删改按钮的权限控制*/
//    @PreAuthorize("@ss.hasPermi('goods:good:add')")
    @Log(title = "货物信息", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody TGoodsInfo tGoodsInfo)
    {
        if(GoodsConstants.NOT_UNIQUE.equals(tGoodsInfoService.checkBundleNumberUnique(tGoodsInfo)))
        {
            return error("新增货物'" + tGoodsInfo.getBundleNumber() + "'失败，捆包号已存在");
        }
        tGoodsInfo.setCreateBy(getNickName());
        int rtn = tGoodsInfoService.insertTGoodsInfo(tGoodsInfo);
        if((rtn > 0) && StringUtils.isNotNull(tGoodsInfo.getEnterWarehouseNumber()))
        {
            rtn = wEnterWarehouseInfoService.updateWEnterTotalWeightPieceByNumber(tGoodsInfo.getEnterWarehouseNumber());
            if(rtn == 0)
            {
                logger.error("goods Add " + "update Enter Total Weight Piece error, EnterWarehouseNumber " + tGoodsInfo.getEnterWarehouseNumber());
            }
        } else {
            logger.error("goods Add " + "insertTGoodsInfo error, tGoodsInfo " + tGoodsInfo);
        }

        return toAjax(rtn);
    }

    /**
     * 修改货物信息
     */
    /*解决入库，货物增删改问题，暂时屏蔽后端权限校验；需增加入库，货物增删改按钮的权限控制*/
//    @PreAuthorize("@ss.hasPermi('goods:good:edit')")
    @Transactional
    @Log(title = "货物信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TGoodsInfo tGoodsInfo)
    {
        if (GoodsConstants.NOT_UNIQUE.equals(tGoodsInfoService.checkBundleNumberUnique(tGoodsInfo)))
        {
            return error("修改货物'" + tGoodsInfo.getBundleNumber() + "'失败，捆包号已存在");
        }
        tGoodsInfo.setUpdateBy(getNickName());
        //logger.debug("XXX tGoodsInfo edit " + tGoodsInfo);
        int rtn = tGoodsInfoService.updateTGoodsInfo(tGoodsInfo);
        if(rtn == 0) {
            logger.error("XXX goods edit " + "update goods edit error, " + tGoodsInfo.getBundleNumber());
            return error("货物修改失败");
        }
        /*if((rtn > 0) && StringUtils.isNotNull(tGoodsInfo.getEnterWarehouseNumber()))
        {
            //rtn = wEnterWarehouseInfoService.updateWEnterTotalWeightPieceByNumber(tGoodsInfo.getEnterWarehouseNumber());
            if(wEnterWarehouseInfoService.updateWEnterTotalWeightPieceByNumber(tGoodsInfo.getEnterWarehouseNumber()) == 0)
            {
                logger.error("XXX edit " + "update Enter Total Weight Piece error");
            }
        }*/
        // 更新入库单据，出库单据，货转单据，货转费记账，出库费记账
        TGoodsInfo goodsInfo = tGoodsInfoService.selectTGoodsInfoByGoodsId(tGoodsInfo.getGoodsId());
        // 更新入库单据
        if(StringUtils.isNotNull(goodsInfo.getEnterWarehouseNumber())) {
            if(wEnterWarehouseInfoService.updateWEnterTotalWeightPieceByNumber(goodsInfo.getEnterWarehouseNumber()) == 0)
            {
                logger.error("XXX edit " + "update Enter Total Weight Piece error, " + goodsInfo.getEnterWarehouseNumber());
            }
        }
        // 更新出库单据
        if(StringUtils.isNotNull(goodsInfo.getExitWarehouseNumber())) {
            if(wExitWarehouseInfoService.updateWExitTotalWeightPieceByNumber(goodsInfo.getExitWarehouseNumber()) == 0)
            {
                logger.error("XXX edit " + "update Exit Total Weight Piece error, " + goodsInfo.getExitWarehouseNumber());
            }
            //logger.debug("XXX goodsInfo edit " + goodsInfo);
            // 需要判断是否已经出库
            if(goodsInfo.getInventoryStatus().equals("已出库")) {
                // 重新计算出库费，仓储费 + 超期费，
                double storageFee = 0.0;
                double weightFact = 0.0;
                //if(goodsInfo.getWeightMode().equals("实际计重")) {
                    weightFact = goodsInfo.getWeight();
                //} else {
                //    weightFact = goodsInfo.getTheoryWeight();
                //}
                if(goodsInfo.getWarehouseType().equals("室内库")) {
                    storageFee = weightFact * goodsInfo.getIndoorWarehousePrice();
                } else {
                    storageFee = weightFact * goodsInfo.getOutdoorWarehousePrice();
                }
                storageFee = Math.round(storageFee * 100.0) / 100.0;
                goodsInfo.setStorageFee(storageFee);

                // 超期费
                double overdueFee = 0.0;
                int overdueDay = goodsInfo.getStorageDay() - goodsInfo.getFreeStorage();
                if(overdueDay < 0) { overdueDay = 0; }
                if(goodsInfo.getOverduePriceMode().equals("吨x天")) {
                    overdueFee = weightFact * goodsInfo.getOverduePrice() * overdueDay;
                } else {
                    overdueFee = weightFact * goodsInfo.getOverduePrice() * overdueDay / 30;
                }
                overdueFee = Math.round(overdueFee * 100.0) / 100.0;
                goodsInfo.setOverdueFee(overdueFee);

                rtn = tGoodsInfoService.updateTGoodsInfo(goodsInfo);
                if(rtn == 0) {
                    logger.error("XXX goods edit " + "update goods storageFee, overdueFee error, " + goodsInfo.getBundleNumber());
                }
                wWarehouseFeeAccountService.recalculateWWarehouseFeeAccountByExitWarehouseNumber(goodsInfo.getExitWarehouseNumber());
            }
        }
        // 更新货转单据
        if(goodsInfo.getGoodsTransferTimes() > 0) {
            String[] goodsTransferIds = goodsInfo.getGoodsTransferIds().split(",");
            for(String goodsTransferId : goodsTransferIds) {
                wGoodsTransferInfoService.updateWTransferTotalWeightPieceByGoodsTransferId(Long.parseLong(goodsTransferId));
            }
        }
        // 重新计算货转费，货转费计算，涉及，收费重量，与不收费重量，无法分清当前货物是否在收费重量内，暂不做处理

        return toAjax(rtn);
    }

    /**
     * 删除货物信息
     */
    /*解决入库，货物增删改问题，暂时屏蔽后端权限校验；需增加入库，货物增删改按钮的权限控制*/
//    @PreAuthorize("@ss.hasPermi('goods:good:remove')")
    @Log(title = "货物信息", businessType = BusinessType.DELETE)
    @DeleteMapping("/{goodsIds}")
    public AjaxResult remove(@PathVariable Long[] goodsIds)
    {
        return toAjax(tGoodsInfoService.deleteTGoodsInfoByGoodsIds(goodsIds));
    }

    /**
     * 更新货物信息，货物所属运单号
     */
    //@PreAuthorize("@ss.hasPermi('goods:good:edit')")
    @Log(title = "货物信息", businessType = BusinessType.UPDATE)
    @PutMapping("/waybill/{goodsIds}/{waybillNumber}")
    public AjaxResult updateWaybillNumber(@PathVariable Long[] goodsIds, @PathVariable String waybillNumber)
    {
//        logger.debug("YYY " + "goodsIds = " + goodsIds);
//        logger.debug("YYY " + "waybillNumber = " + waybillNumber);
        //UPDATE_WAYBILL
//        return toAjax(tGoodsInfoService.updateTGoodsWayBillNumber(goodsIds, waybillNumber));
//        return toAjax(tGoodsInfoService.updateTGoodsInfoByGoodsIds(UPDATE_WAYBILL, goodsIds, waybillNumber));
        int rtn = tGoodsInfoService.updateTGoodsInfoByGoodsIds(UPDATE_WAYBILL, goodsIds, waybillNumber);

        return toAjax(calculateAndUpdateTWayBillNumber(waybillNumber));
    }

    /**
     * 获取货物信息详细信息
     */
    //@PreAuthorize("@ss.hasPermi('goods:good:query')")
    @GetMapping(value = "/waybill/{waybillNumber}")
    public AjaxResult getInfoByWaybillNumber(@PathVariable("waybillNumber") String waybillNumber)
    {
        return success(tGoodsInfoService.selectTGoodsInfoByNumber(1, waybillNumber));
    }

    /**
     * 移除货物信息
     */
    //@PreAuthorize("@ss.hasPermi('goods:good:remove')")
    @Log(title = "货物信息", businessType = BusinessType.REMOVE)
    @DeleteMapping("/waybill/{goodsIds}/{waybillNumber}")
    public AjaxResult removeWaybillNumber(@PathVariable Long[] goodsIds, @PathVariable String waybillNumber)
    {
//        logger.debug("YYY removeWaybillNumber " + "goodsIds = " + goodsIds);
//        logger.debug("YYY removeWaybillNumber " + "waybillNumber = " + waybillNumber);
        int rtn = tGoodsInfoService.removeTGoodsInfoByGoodsIds(REMOVE_WAYBILL, goodsIds);
        return toAjax(calculateAndUpdateTWayBillNumber(waybillNumber));
    }

    private int calculateAndUpdateTWayBillNumber(String waybillNumber) {
//        logger.debug("XXX " + "waybillNumber = " + waybillNumber);
        //double totalWeight = tGoodsInfoService.calculateTotalWeightByWayBillNumber(waybillNumber);
        List<TGoodsInfo> goodsInfoList = tGoodsInfoService.selectTGoodsInfoByNumber(1, waybillNumber);
        int freightNumber = goodsInfoList.size();
        double totalWeight = 0.0;
        for (TGoodsInfo item : goodsInfoList)
        {
            totalWeight = totalWeight + item.getWeight();
        }
//        logger.debug("XXX " + "totalWeight = " + totalWeight);

        TWayBillInfo tWayBillInfo = tWayBillInfoService.selectTWayBillInfoByWayBillNumber(waybillNumber);
        tWayBillInfo.setFreightWeight(Math.round(totalWeight * 1000) /1000.0);
        tWayBillInfo.setFreightNumber(freightNumber);
        //计算应付
        String freightPriceMode = tWayBillInfo.getFreightPriceMode();
        double freightPrice = tWayBillInfo.getFreightPrice();
        double freightAmount = 0.0;
        double primage = tWayBillInfo.getPrimage();
        double freightTotalAmount = 0.0;
        if( (freightPriceMode != null ) && (freightPriceMode.equals(PriceMode.BYTON.getCode())) ){
            freightAmount = freightPrice * totalWeight;
        } else if ( (freightPriceMode != null ) && (freightPriceMode.equals(PriceMode.BYTRUCK.getCode())) )
        {
            freightAmount = freightPrice;
        } else {
            logger.error("XXX " + "Freigh Price Mode error");
        }
        freightTotalAmount = freightAmount + primage;

        tWayBillInfo.setFreightAmount(Math.round(freightAmount * 100) /100.0);
        tWayBillInfo.setFreightTotalAmount(Math.round(freightTotalAmount * 100) /100.0);

        //计算应收
        String settlementPriceMode = tWayBillInfo.getSettlementPriceMode();
        double settlementPrice = tWayBillInfo.getSettlementPrice();
        double settlementAmount = 0.0;
        double primageFreight = tWayBillInfo.getPremium();
        double settlementTotalAmount = 0.0;
        if( (settlementPriceMode != null ) && (settlementPriceMode.equals(PriceMode.BYTON.getCode())) ){
            settlementAmount = settlementPrice * totalWeight;
        } else if ( (settlementPriceMode != null ) && (settlementPriceMode.equals(PriceMode.BYTRUCK.getCode())) )
        {
            settlementAmount = settlementPrice;
        } else {
            logger.error("XXX " + "Settlement Price Mode error");
        }
        settlementTotalAmount = settlementAmount + primageFreight;

        tWayBillInfo.setSettlementAmount(Math.round(settlementAmount * 100) /100.0);
        tWayBillInfo.setSettlementTotalAmount(Math.round(settlementTotalAmount * 100) /100.0);

        return tWayBillInfoService.updateTWayBillInfo(tWayBillInfo);
    }

    /**
     * 更新货物信息，货物所属入库单号
     */
    //@PreAuthorize("@ss.hasPermi('goods:good:edit')")
    @Log(title = "货物信息", businessType = BusinessType.UPDATE)
    @PutMapping("/enternumber/{goodsIds}/{enterWarehouseNumber}")
    public AjaxResult updateEnterWarehouseNumber(@PathVariable Long[] goodsIds, @PathVariable String enterWarehouseNumber, @RequestBody WEnterWarehouseInfo enterWarehouseInfo)
    {
        int rtn = 0;
//        logger.debug("YYY " + "goodsIds = " + goodsIds);
//        logger.debug("YYY " + "enterWarehouseNumber = " + enterWarehouseNumber);
//        logger.debug("YYY " + "enterWarehouseInfo = " + enterWarehouseInfo);
        //UPDATE_ENTERNUMBER
//        rtn = tGoodsInfoService.updateTGoodsInfoByGoodsIds(UPDATE_ENTERNUMBER, goodsIds, enterWarehouseNumber);
        rtn = tGoodsInfoService.updateTGoodsInfoRelEnterWarehouseFieldsByGoodsIds(goodsIds, enterWarehouseInfo);

        return toAjax(rtn);
    }

    /**
     * 移除货物信息
     */
    //@PreAuthorize("@ss.hasPermi('goods:good:remove')")
    @Log(title = "货物信息", businessType = BusinessType.REMOVE)
    @DeleteMapping("/enternumber/{goodsIds}/{enterWarehouseNumber}")
    public AjaxResult removeEnterWarehouseNumber(@PathVariable Long[] goodsIds, @PathVariable String enterWarehouseNumber)
    {
//        logger.debug("YYY removeWaybillNumber " + "goodsIds = " + goodsIds);
//       logger.debug("YYY removeWaybillNumber " + "waybillNumber = " + enterWarehouseNumber);
        int rtn = tGoodsInfoService.removeTGoodsInfoByGoodsIds(REMOVE_ENTERNUMBER, goodsIds);
        return toAjax(rtn);
    }

    /**
     * 更新货物信息，货物入库查验
     */
    //@PreAuthorize("@ss.hasPermi('goods:good:edit')")
    @Log(title = "货物信息", businessType = BusinessType.UPDATE)
    @PutMapping("/entercheck/{goodsIds}/{checkStatus}")
    public AjaxResult updateEnterCheckStatus(@PathVariable Long[] goodsIds, @PathVariable String checkStatus)
    {
//        logger.debug("YYY " + "goodsIds = " + goodsIds);
//        logger.debug("YYY " + "checkStatus = " + checkStatus);
        //UPDATE_ENTERNUMBER, 3
        int rtn = tGoodsInfoService.updateTGoodsInfoByGoodsIds(UPDATE_ENTERCHECK, goodsIds, checkStatus);

        return toAjax(rtn);
    }

    /**
     * 获取货物信息详细信息
     */
    //@PreAuthorize("@ss.hasPermi('goods:good:query')")
    @GetMapping(value = "/enterprint/{enterNumber}")
    public AjaxResult getInfoByEnterNumber(@PathVariable("enterNumber") String enterNumber)
    {
        return success(tGoodsInfoService.selectTGoodsInfoByNumber(2, enterNumber));
    }

    // 出库加货，出库移除，准备移到出库模块
    /**
     * 出库加货，更新货物信息，中出库相关字段，准备移到出库模块
     */
    //@PreAuthorize("@ss.hasPermi('goods:good:edit')")
    @Log(title = "货物信息", businessType = BusinessType.UPDATE)
    @PutMapping("/exitnumber/{goodsIds}/{exitWarehouseNumber}")
    public AjaxResult updateExitWarehouseNumber(@PathVariable Long[] goodsIds, @PathVariable String exitWarehouseNumber, @RequestBody WExitWarehouseInfo wExitWarehouseInfo)
    {
        //logger.debug("XXX exitnumber add goods exitWarehouseInfo" + exitWarehouseInfo);
        WExitWarehouseInfo exitWarehouseInfo = wExitWarehouseInfoService.selectWExitWarehouseInfoByExitWarehouseNumber(exitWarehouseNumber);
        if(StringUtils.isNull(exitWarehouseInfo)) {
            return error("当前作业，已删除，货物加货失败！");
        } else if(exitWarehouseInfo.getJobStatus().equals("3")) {
            return error("当前作业，已确认出库，加货失败！");
        }
        int rtn = tGoodsInfoService.updateTGoodsInfoRelExitWarehouseFieldsByGoodsIds(goodsIds, exitWarehouseNumber, wExitWarehouseInfo, "出库中");

        if((rtn > 0) && StringUtils.isNotNull(exitWarehouseNumber))
        {
            rtn = wExitWarehouseInfoService.updateWExitTotalWeightPieceByNumber(exitWarehouseNumber);
            if(rtn == 0)
            {
                logger.error("exit warehouse Add goods " + "update Exit Total Weight Piece error, exitWarehouseNumber " + exitWarehouseNumber);
            }
        } else {
            logger.error("exit warehouse Add goods " + "updateTGoodsInfoRelExitWarehouseFieldsByGoodsIds error, exitWarehouseNumber " + exitWarehouseNumber + ", goodsIds, " + Arrays.toString(goodsIds));
        }

        return toAjax(rtn);
    }

    /**
     * 出库移除，清空货物信息，中出库相关字段，准备移到出库模块
     */
    //@PreAuthorize("@ss.hasPermi('goods:good:remove')")
    @Log(title = "货物信息", businessType = BusinessType.REMOVE)
    @DeleteMapping("/exitnumber/{goodsIds}/{exitWarehouseNumber}")
    public AjaxResult removeExitWarehouseNumber(@PathVariable Long[] goodsIds, @PathVariable String exitWarehouseNumber)
    {
        String operator = getNickName();
        // 货物移除打印此信息，重点监控，异常移除问题
        logger.info("YYY removeExitWarehouseNumber " + "goodsIds = " + Arrays.toString(goodsIds) + " exitWarehouseNumber = " + exitWarehouseNumber + " operator = " + operator);
        WExitWarehouseInfo exitWarehouseInfo = wExitWarehouseInfoService.selectWExitWarehouseInfoByExitWarehouseNumber(exitWarehouseNumber);
        if(StringUtils.isNull(exitWarehouseInfo)) {
            return error("当前作业，已删除，货物移除失败！");
        } else if(exitWarehouseInfo.getJobStatus().equals("3")) {
            return error("当前作业，已确认出库，移除失败！");
        }
        int rtn = tGoodsInfoService.removeTGoodsExitWarehouseRelFieldByGoodsIds(goodsIds, exitWarehouseNumber, operator);
        if((rtn > 0) && StringUtils.isNotNull(exitWarehouseNumber))
        {
            rtn = wExitWarehouseInfoService.updateWExitTotalWeightPieceByNumber(exitWarehouseNumber);
            if(rtn == 0)
            {
                logger.error("exit warehouse Remove goods " + "update Exit Total Weight Piece error, exitWarehouseNumber " + exitWarehouseNumber);
            }
        } else {
            logger.error("exit warehouse Remove goods " + "removeTGoodsExitWarehouseRelFieldByGoodsIds error, exitWarehouseNumber " + exitWarehouseNumber + ", goodsIds, " + Arrays.toString(goodsIds));
        }

        return toAjax(rtn);
    }

    /**
     * 更新货物信息，货物入库查验
     */
    //@PreAuthorize("@ss.hasPermi('goods:good:edit')")
    @Log(title = "货物信息", businessType = BusinessType.UPDATE)
    @PutMapping("/exitcheck/{goodsIds}/{checkStatus}")
    public AjaxResult updateExitCheckStatus(@PathVariable Long[] goodsIds, @PathVariable String checkStatus)
    {
//        logger.debug("YYY " + "goodsIds = " + goodsIds);
//        logger.debug("YYY " + "checkStatus = " + checkStatus);
        //UPDATE_EXITCHECK, 5
        int rtn = tGoodsInfoService.updateTGoodsInfoByGoodsIds(UPDATE_EXITCHECK, goodsIds, checkStatus);

        return toAjax(rtn);
    }

    /**
     * 获取货物信息详细信息
     */
    //@PreAuthorize("@ss.hasPermi('goods:good:query')")
    @GetMapping(value = "/exitprint/{exitNumber}")
    public AjaxResult getInfoByExitNumber(@PathVariable("exitNumber") String exitNumber)
    {
        return success(tGoodsInfoService.selectTGoodsInfoByNumber(3, exitNumber));
    }

    /**
     * 获取货物信息详细信息
     */
    //@PreAuthorize("@ss.hasPermi('goods:good:query')")
    @GetMapping(value = "/transfer/{goodsTransferId}")
    public TableDataInfo getGoodsInfoByTransferId(@PathVariable("goodsTransferId") Long goodsTransferId)
    {
        startPage();
        List<TGoodsInfo> list = tGoodsInfoService.selectTGoodsInfoByTransferId(goodsTransferId);
        return getDataTable(list);
    }

    /**
     * 获取货物信息详细信息
     */
    //@PreAuthorize("@ss.hasPermi('goods:good:query')")
    @GetMapping(value = "/transferprint/{goodsTransferId}")
    public AjaxResult getGoodsPrintByTransferId(@PathVariable("goodsTransferId") Long goodsTransferId)
    {
        List<TGoodsInfo> list = tGoodsInfoService.selectTGoodsInfoByTransferId(goodsTransferId);
        return success(list);
    }

    /**
     * 物理删除货物信息
     */
    //@PreAuthorize("@ss.hasPermi('goods:good:remove')")
/*    @Log(title = "货物信息", businessType = BusinessType.DELETE)
    @DeleteMapping("/ext/{goodsIds}")
    public AjaxResult removeExt(@PathVariable Long[] goodsIds)
    {
//        logger.debug("YYY " + "removeExt = " + goodsIds[0]);
        int rtn = 0;
        TGoodsInfo tGoodsInfo = tGoodsInfoService.selectTGoodsInfoByGoodsId(goodsIds[0]);
//        logger.debug("YYY " + "removeExt tGoodsInfo = " + tGoodsInfo);

        rtn = tGoodsInfoService.deleteTGoodsInfoExtByGoodsIds(goodsIds);

        if((rtn > 0) && StringUtils.isNotNull(tGoodsInfo) && StringUtils.isNotNull(tGoodsInfo.getEnterWarehouseNumber()))
        {
            rtn = wEnterWarehouseInfoService.updateWEnterTotalWeightPieceByNumber(tGoodsInfo.getEnterWarehouseNumber());
            if(rtn == 0)
            {
                logger.error("XXX del " + "update Enter Total Weight Piece error");
            }
        }
        return toAjax(rtn);
    }
*/
    /**
     * 查询货物信息列表，履历
     */
//    @PreAuthorize("@ss.hasPermi('goods:good:list')")
    @GetMapping("/tracelist")
    public TableDataInfo tracelist(TGoodsInfo tGoodsInfo)
    {
        String bundleNumber = tGoodsInfo.getBundleNumber();
        if(StringUtils.isNotEmpty(bundleNumber)) {
            tGoodsInfo.setBundleNumber(bundleNumber.replace(",", "|"));
        }
       startPage();
        List<TGoodsInfo> list = tGoodsInfoService.selectTGoodsInfoTraceList(tGoodsInfo);
        return getDataTable(list);
    }

    /**
     * 批量新增货物
     */
//    @PreAuthorize("@ss.hasPermi('goods:good:add')")
    @Log(title = "货物信息", businessType = BusinessType.INSERT)
    @PostMapping("/batchadd")
    public AjaxResult batchadd(@RequestBody TGoodsInfo tGoodsInfo)
    {
        String vehicle = tGoodsInfo.getEnterWarehouseVehicle().substring(1);
        int number = tGoodsInfo.getNumberOfPiece();
        int rtn = 0;
        Double weight = Math.round(tGoodsInfo.getWeight()/number*1000)/1000.0;
        tGoodsInfo.setWeight(weight);
        tGoodsInfo.setNumberOfPiece(1);
        tGoodsInfo.setCreateBy(getNickName());
        for(int i=0;  i<number; i++)
        {
            tGoodsInfo.setBundleNumber(OrderUtils.getOrderNumber(vehicle, "-"));
            rtn = tGoodsInfoService.insertTGoodsInfo(tGoodsInfo);
        }

        return toAjax(rtn);
    }

    /**
     * 获取货物重量合计
     */
    //@PreAuthorize("@ss.hasPermi('goods:good:query')")
    @GetMapping(value = "/goodsweightsum")
    public AjaxResult goodsWeightSum(TGoodsInfo tGoodsInfo)
    {
        List<TGoodsWeightSum> goodsWeightSumList = tGoodsInfoService.getWeightSumByGoodsInfo(tGoodsInfo);
        if(StringUtils.isEmpty(tGoodsInfo.getInventoryStatus())) {
            double enterWarehouseWeight = 0.0;
            Iterator<TGoodsWeightSum> iterator = goodsWeightSumList.iterator();
            while(iterator.hasNext()) {
                //logger.debug("GGG " + "getWeightSumByInventoryStatus = " + iterator.next());
                //String
                TGoodsWeightSum goodsWeightSum = JSONObject.parseObject(JSON.toJSONString(iterator.next()), TGoodsWeightSum.class);
                /*if (goodsWeightSum.getInventoryStatus().equals("已在库")) {
                    enterWarehouseWeight = enterWarehouseWeight + goodsWeightSum.getWeightSum();
                } else if (goodsWeightSum.getInventoryStatus().equals("已出库")) {
                    enterWarehouseWeight = enterWarehouseWeight + goodsWeightSum.getWeightSum();
                } else if (goodsWeightSum.getInventoryStatus().equals("出库中")) {
                    enterWarehouseWeight = enterWarehouseWeight + goodsWeightSum.getWeightSum();
                } else if (goodsWeightSum.getInventoryStatus().equals("货转中")) {
                    enterWarehouseWeight = enterWarehouseWeight + goodsWeightSum.getWeightSum();
                }*/
                if(goodsWeightSum.getInventoryStatus().matches("已在库|已出库|出库中|货转中")) {
                    enterWarehouseWeight = enterWarehouseWeight + goodsWeightSum.getWeightSum();
                }
            }

            if (Double.compare(enterWarehouseWeight, 0) != 0.0) {
                TGoodsWeightSum tGoodsWeightSum = new TGoodsWeightSum();

                tGoodsWeightSum.setInventoryStatus("已入库");
                tGoodsWeightSum.setWeightSum(Math.round(enterWarehouseWeight * 1000.0) / 1000.0);
                goodsWeightSumList.add(tGoodsWeightSum);
            }
        }

        //logger.debug("GGG " + "getWeightSumByInventoryStatus = " + goodsWeightSumList);
        return success(goodsWeightSumList);
    }

    /**
     * 查询日出库量，关联货物信息
     */
    //@PreAuthorize("@ss.hasPermi('goods:good:query')")
    @GetMapping(value = "/dayexitstatistic/{dayExitStatisticId}")
    public TableDataInfo dayexitstatistic(@PathVariable("dayExitStatisticId") Long dayExitStatisticId, TGoodsInfo tGoodsInfo)
    {
        startPage();
        List<TGoodsInfo> list = tGoodsInfoService.selectTGoodsInfoByDayExitStatisticId(dayExitStatisticId, tGoodsInfo);
        return getDataTable(list);
    }

    /**
     * 查询月出库量，关联货物信息
     */
    //@PreAuthorize("@ss.hasPermi('goods:good:query')")
    @GetMapping(value = "/monthexitstatistic/{monthExitStatisticId}")
    public TableDataInfo monthexitstatistic(@PathVariable("monthExitStatisticId") Long monthExitStatisticId, TGoodsInfo tGoodsInfo)
    {
        startPage();
        List<TGoodsInfo> list = tGoodsInfoService.selectTGoodsInfoByMonthExitStatisticId(monthExitStatisticId, tGoodsInfo);
        return getDataTable(list);
    }

    /**
     * 理货修改库位信息
     */
//    @PreAuthorize("@ss.hasPermi('goods:good:edit')")
    @Log(title = "货物信息", businessType = BusinessType.UPDATE)
    @PutMapping("/tally/{goodsIds}")
    public AjaxResult tally(@PathVariable Long[] goodsIds, @RequestBody TGoodsInfo tGoodsInfo)
    {
        tGoodsInfo.setUpdateBy(getNickName());
        return toAjax(tGoodsInfoService.tallyTGoodsInfoByGoodsIds(goodsIds, tGoodsInfo));
    }

    /**
     * 查询货物信息列表，移动端模糊查询，捆包号
     */
//    @PreAuthorize("@ss.hasPermi('goods:good:list')")
    @GetMapping("/listformp")
    public TableDataInfo listformp(TGoodsInfo tGoodsInfo)
    {
        startPage();
        List<TGoodsInfo> list = tGoodsInfoService.selectTGoodsInfoListForMiniProgram(tGoodsInfo);
        return getDataTable(list);
    }

    /**
     * 拆分货物信息
     */
//    @PreAuthorize("@ss.hasPermi('goods:good:add')")
    @Log(title = "货物信息", businessType = BusinessType.SPLIT)
    @PostMapping("/split/{numberOfSplit}/{splitWeight}")
    public AjaxResult split(@PathVariable Integer numberOfSplit, @PathVariable Double splitWeight, @RequestBody TGoodsInfo tGoodsInfo)
    {
        //logger.debug("XXX " + "split numberOfSplit = " + numberOfSplit);
        //logger.debug("XXX " + "split splitWeight = " + splitWeight);
        int rtn = tGoodsInfoService.splitGoodsInfoByNumberOfSplit(numberOfSplit, splitWeight, tGoodsInfo);
        return rtn > 0 ? toAjax(rtn) : error("当前货物，已被其人拆分，此次拆分失败！");
    }

    /**
     * 查询货物信息列表，模糊搜索，单个捆包号
     */
    @PreAuthorize("@ss.hasPermi('goods:good:list')")
    @GetMapping("/listext")
    public TableDataInfo listext(TGoodsInfo tGoodsInfo)
    {
        //logger.debug("GGG " + "listext = " + tGoodsInfo);
        String bundleNumber = tGoodsInfo.getBundleNumber();
        if(StringUtils.isNotEmpty(bundleNumber)) {
            tGoodsInfo.setBundleNumber(bundleNumber.replace(",", "|"));
        }
        startPage();
        List<TGoodsInfo> list = tGoodsInfoService.selectTGoodsInfoListExt(tGoodsInfo);
        return getDataTable(list);
    }

    /**
     * 查询货物信息列表，模糊搜索，多个捆包号
     */
    @PreAuthorize("@ss.hasPermi('goods:good:list')")
    @GetMapping("/listfuzzy")
    public TableDataInfo listfuzzy(TGoodsInfo tGoodsInfo)
    {
        //logger.debug("GGG " + "listfuzzy = " + tGoodsInfo);
        String bundleNumber = tGoodsInfo.getBundleNumber();
        if(StringUtils.isNotEmpty(bundleNumber)) {
            tGoodsInfo.setBundleNumber(bundleNumber.replace(",", "|"));
//            logger.debug("XXX " + "tGoodsInfo = " + tGoodsInfo.getBundleNumber());
        }

        startPage();
        List<TGoodsInfo> list = tGoodsInfoService.selectTGoodsInfoListByMultipleBuddleNumber(tGoodsInfo);
        return getDataTable(list);
    }

    /**
     * 查询盘库，关联货物信息
     */
    //@PreAuthorize("@ss.hasPermi('goods:good:query')")
    @GetMapping(value = "/inventory/{checkGoodsId}")
    public TableDataInfo inventory(@PathVariable("checkGoodsId") Long checkGoodsId, TGoodsInfo tGoodsInfo)
    {
        startPage();
        List<TGoodsInfo> list = tGoodsInfoService.selectTGoodsInfoByCheckGoodsId(checkGoodsId, tGoodsInfo);
        return getDataTable(list);
    }

}
